package com.iring.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 将错误信息处理请求重定向到首页
 * 处理异常拦截器未处理的错误
 *
 * @author wanggan
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MainsiteErrorController implements ErrorController {

    private ErrorAttributes errorAttributes;

    /**
     * 初始化
     *
     * @param errorAttributes
     *            错误属性操作
     */
    @Autowired
    public MainsiteErrorController(ErrorAttributes errorAttributes) {
        Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
        this.errorAttributes = errorAttributes;
    }

    /**
     * 处理json（异步）请求，返回错误代码和json的错误信息描述
     *
     * @param request
     *            用户请求信息描述
     * @return 完整的http响应信息
     */
    @RequestMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> body = errorAttributes.getErrorAttributes(requestAttributes, false);
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(body, status);
    }

    /**
     * 获取错误编码
     *
     * @param request
     *            用户请求信息描述
     * @return 状态信息
     */
    private HttpStatus getStatus(HttpServletRequest request) {

        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

    /**
     * {@inheritDoc}<br>
     * 实现错误路径,暂时无用
     */
    @Override
    public String getErrorPath() {
        return "/error";
    }

}
